<template>
  <Dialog v-model="visible" :title="title" width="800">
    <el-form ref="formRef" v-loading="loading" :model="form" :rules="formRules" label-width="100px">
      <el-form-item label="标 题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="所属栏目" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择">
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内 容" prop="content">
        <Editor :model-value="form.content" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="loading || !form.title" type="primary" @click="submitForm"
        >确 定</el-button
      >
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="ArticleUpdate" setup>
import * as Api from '@/api/userCenter/content/article'

import * as CategoryApi from '@/api/userCenter/content/category'

const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const title = ref(`编辑信息`) // 弹窗的标题
const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const form = ref({
  id: '',
  title: '',
  content: '',
  categoryId: ''
})
const formRules = reactive({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const categoryOptions = ref<any[]>()

/** 打开弹窗 */
const open = async (id?: string) => {
  getCategoryOptions()
  visible.value = true
  title.value = '编辑文章'

  resetForm()
  // 修改时,设置数据
  if (id) {
    loading.value = true
    form.value.id = id
    try {
      let val = await Api.getById(id)
      if (val) {
        form.value = val
      }
    } catch (t) {
      console.log(t)
    } finally {
      loading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  loading.value = true
  try {
    const data = form.value as unknown as Api.Model
    await Api.update(data)
    message.success(`操作成功`)
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (t) {
    console.log(t)
    loading.value = false
    message.error('提交表单失败')
  } finally {
    loading.value = false
  }
}

/** 重 置表单 */
const resetForm = () => {
  form.value = {
    id: '',
    title: '',
    content: '',
    categoryId: ''
  }
  formRef.value?.resetFields()
}

const getCategoryOptions = async () => {
  categoryOptions.value = []
  categoryOptions.value = await CategoryApi.arr()
}
</script>
